package com.vip8.recorder.service.utils;

/**
 * 邀请码工具类
 */
public class InviteCodeUtil {

    private final static char[] INVITE_DICT = new char[]{'H', 'V', 'E', 'S', '8', 'A', 'D', 'Z', '2', 'X', 'C', '7', 'P',
            '5', 'K', '3', 'M', 'J', 'U', 'F', 'R', '4', 'W', 'Y', '9', 'L', 'T', 'N', '6', 'B', 'G', 'Q'};

    private final static int DICT_LEN = 32;


    /**
     * 通过id生成code
     *
     * @param id
     * @return
     */
    public static String idToCode(Long id) {
        String code = "";
        if (id == null || id == 0) {
            return code;
        }
        // 当id除以数组长度结果大于0，则进行取模操作，并以取模的值作为数组的坐标获得对应的字符
        while (id / DICT_LEN > 0) {
            int index = (int) (id % DICT_LEN);
            code = INVITE_DICT[index] + code;
            id /= DICT_LEN;
        }
        code = INVITE_DICT[(int) (id % DICT_LEN)] + code;

        return code;
    }

    /**
     * 将编码还原成id
     *
     * @param code
     * @return
     */
    public static long codeToId(String code) {
        char[] charArray = code.toCharArray();
        long result = 0;
        for (int i = 0; i < charArray.length; i++) {
            int index = 0;
            for (int j = 0; j < DICT_LEN; j++) {
                if (charArray[i] == INVITE_DICT[j]) {
                    index = j;
                    break;
                }
            }
            if (i > 0) {
                result = result * DICT_LEN + index;
            } else {
                result = index;
            }
        }

        return result;
    }

}
